package login

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

func Login() {
	url := "https://www.itslaw.com/api/auth/login"
	// json
	contentType := "application/json"
	data := `{"phoneNum":"xxx","password":"xxxx","remember":true}`
	resp, err := http.Post(url, contentType, strings.NewReader(data))
	if err != nil {
		fmt.Println("post failed, err:%v\n", err)
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed,err:%v\n", err)
		return
	}
	var v LoginRes
	//读取的数据为json格式，需要进行解码
	json.Unmarshal(b, &v)
	//var ttt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxNzYwMjY1ODIzMyJ9.t2JkpAfO9yh1SZaP9nFZQKsJNg_p3nP00A3qWuECjkU"
	//写入到文件中
	var token = v.Data.Token
	fmt.Println(token)
	f, err := os.OpenFile("login/token.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) //打开文件
	if err != nil {
		fmt.Println("OpenFile token.txt failed,err:%v\n", err)
		return
	}
	_, error := io.WriteString(f, token) //写入文件(字符串)
	if error != nil {
		fmt.Println("WriteString failed,err:%v\n", err)
		return
	}
}

type LoginRes struct {
	Result struct{}
	Data   struct {
		Token string
	}
}
